package org.halk.job_client.component;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.halk.job_client.annotion.BiJob;
import org.halk.job_client.annotion.BiJobMapping;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * 启动时扫描带有定时任务注解的类
 * @Author haozhu7
 * @Date 2024/9/30 15:05
 **/
@Slf4j
@Component
public class JobRunner implements ApplicationRunner {

    private final ApplicationContext applicationContext;

    @Value("${spring.application.name}")
    private String server;

    public JobRunner(ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
    }

    @Override
    public void run(ApplicationArguments args) throws Exception {
        JobContext.setServer(applicationContext.getApplicationName());
        loadClass(applicationContext.getBeanNamesForAnnotation(BiJob.class));
        JobContext.setServer(server);
    }

    private void loadClass(String[] beanNamesForAnnotation) {
        for (String beanName : beanNamesForAnnotation) {
            Object bean = applicationContext.getBean(beanName);
            log.info("加载定时任务类：" + beanName);

            Method[] methods = bean.getClass().getDeclaredMethods();
            for (Method method : methods) {
                if (method.isAnnotationPresent(BiJobMapping.class)) {
                    //是否使用了具体的注解
                    BiJobMapping annotation = method.getAnnotation(BiJobMapping.class);
                    String scheduleId = annotation.value();
                    if (StringUtils.isEmpty(scheduleId)) {
                        continue;
                    }
                    //定时方法id对应得bean放入map
                    JobContext.putJobClass(scheduleId, bean);
                }
            }
        }
    }
}
